package com.cicdi.core.util;

import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * csv文件读取类
 *
 * @author haypo
 * @date 2020/12/3
 */
@Slf4j
public class CsvReaderUtil {
    CsvReader csvReader;

    /**
     * 初始化csv文件读取器
     *
     * @param fileName 文件路径
     * @param readHead 是否读取标题
     * @throws IOException io异常
     */
    public CsvReaderUtil(String fileName, boolean readHead) throws IOException {
        File file = new File(fileName);
        csvReader = new CsvReader(fileName, ',', StandardCharsets.UTF_8);
        if (readHead) {
            csvReader.readHeaders();
        }
        log.info("已读取csv文件!");
    }

    /**
     * 读取文件到list
     *
     * @return 读取的数据
     */
    public List<String[]> read() {
        List<String[]> data = new ArrayList<>();
        try {
            while (csvReader.readRecord()) {
                String[] strs = csvReader.getValues();
                data.add(strs);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return data;
    }
}
